package com.shiyi.controller;

import com.baomidou.mybatisplus.annotation.TableName;
import com.shiyi.common.ResponseResult;
import com.shiyi.service.RedisService;
import com.shiyi.service.UserService;
//import com.shiyi.service.impl.CacheUserServiceImpl;
import com.shiyi.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/myDemo")
@Api(tags = "我的测试接口")
@RequiredArgsConstructor
@Slf4j
public class MyDemoController {


    public static void main(String[] args) {
        try {
            // 加载字体文件
            File fontFile = new File("D:\\数藏项目\\NFTurbo_Client\\static\\font.ttf");
            Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);

            // 获取字体名称
            String fontName = font.getFontName();
            System.out.println("Font Name: " + fontName);
        } catch (FontFormatException | IOException e) {
            e.printStackTrace();
        }
    }

    private final UserService userService;


    private final RedisTemplate<String,String> redisTemplate;


    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private PayFactory payFactory;

    @RequestMapping("/getLockMsg")
    public ResponseResult getLockMsg() {

        userService.getMyTest();
        return ResponseResult.success();
    }

    @RequestMapping("/getLockMsg1")
    public ResponseResult getLockMsg1() {
        userService.getMyTest1();
//        double v = 10 / 1e13;
        return ResponseResult.success();
    }

    @RequestMapping("/joinIn")
    public ResponseResult joinIn() {
        userService.joinIn();
        return ResponseResult.success();
    }

    @RequestMapping("/startClub")
    public ResponseResult startClub() {
        userService.startClub();
        return ResponseResult.success();
    }


    @RequestMapping("/order")
    public ResponseResult order(@RequestParam("token") String token) {
        userService.order(token);
        return ResponseResult.success();
    }

    @GetMapping("/getEntityTables")
    public Map<String, String> getEntityTables() {
        Map<String, String> entityTables = new HashMap<>();

        String[] beanNames = applicationContext.getBeanNamesForAnnotation(TableName.class);
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            String tableName = bean.getClass().getAnnotation(TableName.class).value();
            entityTables.put(bean.getClass().getSimpleName(), tableName);
        }

        return entityTables;
    }


    @PostMapping(value = "/pay")
    public ResponseResult pay(@RequestBody PayParams params) {
        PayServiceAbstract payServiceAbstract = payFactory.getFactory(params.getName());
        payServiceAbstract.pay(params);
        return ResponseResult.success();
    }



    @PostMapping(value = "/oom")
    public ResponseResult oom() {
        // 字体包文件的路径和名称
        String fontPath = "E:/hy132/f002.ttf";
        try {
            // 1. 使用字体文件路径创建一个File对象
            File fontFile = new File(fontPath);

            // 2. 使用Font.createFont方法创建字体对象。
            Font customFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);

            // 3. 可选：调整字体的大小。
            customFont = customFont.deriveFont(12.0f);

            // 在这里使用你的字体对象
            System.out.println("Loaded custom font: " + customFont.getName());
            Thread.sleep(1000);
        } catch (IOException | FontFormatException | InterruptedException e) {
            e.printStackTrace();
        }
        return ResponseResult.success();
    }

//    private final CacheUserServiceImpl cacheUserService;

    /**
     * 代理模式
     * @return
     */
//    @GetMapping("/proxyMode")
//    public ResponseResult proxyMode(){
//        // 使用你代理客户端
//        ResponseResult currentUserInfo = cacheUserService.getCurrentUserInfo();
//        return currentUserInfo;
//    }


    private ExecutorService executorService = Executors.newCachedThreadPool();
    /**
     * 数据库 死锁
     * @return
     */
    @GetMapping("/dataSourceDeadLock")
    public ResponseResult dataSourceDeadLock() throws InterruptedException {

        redisTemplate.opsForValue().decrement("key1");
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        List<String> list = new ArrayList<>();
        redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),
                list,
                "hello","HELLO2"
        );
//        executorService.execute(()->{
//            try {
//                userService.dataSourceDeadLock();
//                log.info("dataSourceDeadLock1  完成");
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        });
//        Runnable runnable = () -> {
//            try {
//                userService.dataSourceDeadLock2();
//                log.info("dataSourceDeadLock2  完成");
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        };
//        executorService.execute(runnable);

        userService.dataSourceDeadLock();
//        userService.dataSourceDeadLock2();
        return ResponseResult.success();
    }

    @GetMapping("/dataSourceDeadLock2")
    public ResponseResult dataSourceDeadLock2() throws InterruptedException {
        userService.dataSourceDeadLock2();
//        userService.dataSourceDeadLock();
        return ResponseResult.success();
    }

}
